<template>
    <view>
        <Navbar title="我的待办" bgColor="#fff" :h5Show="false" :autoBack="true" :border="true"></Navbar>
        <!-- 左右滑动切换月份 -->
        <view @touchstart="handleTouchStart" @touchend="handleTouchEnd">
            <view class="titleBox">
                <view class="title">{{ currentYear }}.{{ currentMonth }}</view>
            </view>
            <view class="week">
                <view v-for="(item, index) in week" :key="index">{{ item }}</view>
            </view>
            <!-- 日历 -->
            <view class="calendarbBox">
                <view class="singleDay" v-for="(item, index) in currentMonthAllDate" :key="index"
                    @tap="selectedDate(item.date)">
                    <text class="dayTextB" v-if="item.month != 'current'">{{ item.number }}</text>
                    <text class="dayTextA"
                        v-if="item.month == 'current' && String(currentToday) == String(item.date)">{{
                            item.number }}</text>
                    <text class="dayText" v-if="item.month == 'current' && String(currentToday) != String(item.date)">{{
                        item.number }}</text>
                    <view class="point" v-if="item.isPlan"></view>
                    <view class="selectedDayBGColor" v-if="String(currentToday) == String(item.date)"></view>
                    <view class="pointA" v-if="String(currentToday) == String(item.date) && item.isPlan"></view>
                </view>
            </view>
        </view>
        <view style="width: 20%; float:inline-end; margin: 2vh 3vh 0 0;">
            <u-button type="primary" text="添加待办" size="small" icon="plus" @click="addSchedule(currentToday)"></u-button>
        </view>
        <view class="u-form-data" ref="formDataContainer">
            <!-- <view v-show="hasReminder"> -->
            <u-form :rules="rules" labelWidth="70" ref="uForm" v-for="(item, index) in scheduleList" :key="index"
                :model="item">
                <u-form-item label="待办标题" prop="title">
                    <u-input ref="titleInput" type="text" v-model="item.title" placeholder="请输入待办标题"
                        style="padding: 10rpx;" />
                </u-form-item>
                <u-form-item label="待办时间" prop="reminderTime" @click="showDateTimePicker(index)">
                    <u-input type="text" v-model="item.reminderTime" placeholder="请选择待办时间"
                        style="padding: 10rpx; font-size: 28rpx; color: #333; pointer-events:none" readonly />
                </u-form-item>
                <!-- 弹出时间选择器 -->
                <u-datetime-picker ref="`time${index}`" v-model="item.reminderTime" mode="time"
                    :show="showTimePicker[index]" @confirm="onTimeConfirm($event, item, index)"
                    @cancel="close($event, item, index)" @change="onTimeChange($event, item, index,)">
                </u-datetime-picker>
                <u-form-item label="待办内容" prop="remark">
                    <u-textarea v-model="item.remark" placeholder="请输入待办内容" maxlength="200" count
                        confirm-type="send"></u-textarea>
                </u-form-item>
                <u-form-item>
                    <button type="submit" @click="deleteReminder(item, index)"
                        style="width: 45%; background-color: red; color: #fff;">删除</button>
                    <button type="submit" @click="submitReminder(item)" style="width: 45%;">提交待办</button>

                </u-form-item>
            </u-form>
            <!-- </view> -->
            <u-empty mode="news" text="暂无待办" style="padding-top: 8vh;" v-show="scheduleList.length == 0"></u-empty>

        </view>
    </view>
</template>
<script>
import Navbar from '@/components/navbar/Navbar';
import moment from 'moment';
import { getUserInfoList, getListForUserList, postTodoSchedule, putTodoSchedule, delTodoSchedule, getlistForMonth } from '@/api/api';
export default {
    components: {
        Navbar,
    },
    data() {
        const now = new Date();
        const hours = String(now.getHours()).padStart(2, '0');
        const minutes = String(now.getMinutes()).padStart(2, '0');
        const currentTime = `${hours}:${minutes}`;
        return {
            // 周列表
            week: ['日', '一', '二', '三', '四', '五', '六'],
            currentYear: '',
            currentMonth: '',
            currentToday: null,
            currentMonthNum: 0,
            monthFirstDayCurrentWeek: 0,
            monthFinallyDayCurrentWeek: 0,
            currentMonthAllDate: [],
            lastMonthDateNumber: 0,
            nextMonthDateNumber: 0,
            showMonthOrWeek: false, // true 表示显示周，false 显示月
            currentTodayDate: null,
            initialX: 0,
            reminderForm: {
                title: '',
                time: currentTime,
                content: ''
            },
            rules: {
                'reminderForm.title': [
                    { required: true, message: '请输入待办标题', trigger: 'blur' }
                ],
                'reminderForm.time': [
                    { required: true, message: '请选择待办时间', trigger: 'change' }
                ],
                'reminderForm.content': [
                    { required: true, message: '请输入待办内容', trigger: 'blur' }
                ]
            },
            reminders: [],
            showTimePicker: [], // 控制时间选择器显示隐藏
            formattedTime: '',
            // 是否有待办
            hasReminder: false,
            time: [],
            scheduleList: [],
            userInfo: {},
            monthTodoList: [],
        };
    },
    mounted() {
        this.getlistForMonth(moment().format('YYYY-MM'))
        this.currentTodayDate = new Date(new Date(new Date().toLocaleDateString()).getTime());
        this.getAllDatesOfCurrentMonth(this.currentTodayDate);
        this.getUserInfoList();
        this.getListForUserList(moment().format('YYYY-MM-DD'));


    },
    methods: {

        // 按月获取所有待办
        getlistForMonth(month) {
            getlistForMonth({ date: month }).then(res => {
                if (res.code == 200) {
                    this.monthTodoList = res.data
                    this.currentMonthAllDate = this.currentMonthAllDate.map(item => {
                        // 修正：使用 item.date 而非 item.data
                        const currentDate = moment(item.date).format('YYYY-MM-DD');
                        // 存在则返回 1，否则返回 0
                        item.isPlan = this.monthTodoList.includes(currentDate) ? true : false;
                        return item;
                    });
                } else {
                    uni.showToast({
                        title: res.msg,
                        icon: 'none'
                    })
                }
            })
        },

        // 删除待办
        deleteReminder(item, index) {
            const id = item.id
            if (id) {
                delTodoSchedule(id).then(res => {
                    if (res.code == 200) {
                        uni.showToast({
                            title: '删除成功',
                            icon: 'none'
                        })
                        setTimeout(() => {
                            this.getListForUserList(item.createDate);

                        }, 1000);
                    } else {
                        uni.showToast({
                            title: res.msg,
                            icon: 'none'
                        })
                    }
                })
            } else {
                this.scheduleList.splice(index, 1)
            }
        },

        // 获取列表
        getListForUserList(createDate) {
            getListForUserList({ createDate: moment(createDate).format('YYYY-MM-DD') }).then(res => {
                if (res.code == 200) {
                    this.scheduleList = res.data
                } else {
                    uni.showToast({
                        title: res.msg,
                        icon: 'none'
                    })
                }
            })
        },

        // 获取当前登录人的信息
        getUserInfoList() {
            getUserInfoList().then(res => {
                console.log('获取当前登录人的信息', res);
                this.userInfo = res.data;
            })

        },



        // 点击添加待办按钮
        addSchedule(data) {
            this.hasReminder = true;
            const hasEmptyId = this.scheduleList.some(item => !item.id);
            if (hasEmptyId) {
                alert('请把待办提交后再添加新的待办');
                return false;
            } else {
                // 关键修改：使用 unshift 将新数据插入数组开头
                this.scheduleList.unshift({
                    "id": '',
                    "userId": this.userInfo.id,
                    "createTime": '',
                    "updateTime": '',
                    "createDate": data,
                    "reminderTime": '',
                    "title": '',
                    "remark": ''
                });
                this.showTimePicker = new Array(this.scheduleList.length).fill(false);

            }
        },

        // 提交按钮
        submitReminder(value) {
            console.log("valuevalue", value)
            // 检查 createDate 是否存在且 moment 能正确解析
            if (value.createDate) {
                // 转换为 'YYYY-MM-DD HH:mm:ss' 格式，你可按需修改
                value.createDate = moment(value.createDate).format('YYYY-MM-DD');
            }

            if (value.id == '') {
                postTodoSchedule(value).then(res => {
                    if (res.code == 200) {
                        uni.showToast({
                            title: '添加成功',
                            icon: 'none'
                        })
                        setTimeout(() => {
                            this.getListForUserList(value.createDate);

                        }, 1000);
                    } else {
                        uni.showToast({
                            title: res.msg,
                            icon: 'none'
                        })
                    }
                })
            } else {
                putTodoSchedule(value).then(res => {
                    if (res.code == 200) {
                        uni.showToast({
                            title: '修改成功',
                            icon: 'none'
                        })
                        setTimeout(() => {
                            this.getListForUserList(value.createDate);

                        }, 1000);
                    } else {
                        uni.showToast({
                            title: res.msg,
                            icon: 'none'
                        })
                    }
                })
            }
        },

        showDateTimePicker(index) {
            this.$nextTick(() => {
                this.showTimePicker[index] = true;
                this.$forceUpdate()
            })
        },

        onTimeChange(timeStr, item, index) {
            // item.reminderTime = this.formatTimeDisplay(timeStr);
        },

        formatTimeDisplay(data) {
            const timeStr = data.value; // 获取实际时间字符串
            if (!timeStr || typeof timeStr !== 'string') return '请选择提醒时间';
            return `${timeStr}`;
        },

        onTimeConfirm(data, item, index) {
            const timeStr = data.value;
            item.reminderTime = timeStr;
            item.reminderTime = this.formatTimeDisplay(data);
            this.$nextTick(() => {
                this.showTimePicker[index] = false;
                this.$forceUpdate()
            })
        },

        close(data, item, index) {
            this.$nextTick(() => {
                this.showTimePicker[index] = false;
                this.$forceUpdate()
            })
        },

        handleTouchStart(event) {
            this.initialX = event.changedTouches[0].clientX;
        },
        handleTouchEnd(event) {
            const currentX = event.changedTouches[0].clientX;
            if (currentX - this.initialX > 20) {
                // 右滑：上个月
                const currentMonthNum = parseInt(this.currentMonth, 10); // 或使用 this.currentMonthNum
                const year = currentMonthNum === 1 ? this.currentYear - 1 : this.currentYear;
                const month = currentMonthNum === 1 ? 12 : currentMonthNum - 1;
                const formattedMonth = month < 10 ? '0' + month : String(month);
                this.currentTodayDate = new Date(`${year}/${formattedMonth}/1`);
                this.getAllDatesOfCurrentMonth(this.currentTodayDate);

            } else if (this.initialX - currentX > 20) {
                // 左滑：下个月
                const currentMonthNum = parseInt(this.currentMonth, 10); // 同理
                const year = currentMonthNum === 12 ? this.currentYear + 1 : this.currentYear;
                const month = currentMonthNum === 12 ? 1 : currentMonthNum + 1;
                const formattedMonth = month < 10 ? '0' + month : String(month);
                this.currentTodayDate = new Date(`${year}/${formattedMonth}/1`);
                this.getAllDatesOfCurrentMonth(this.currentTodayDate);
            }
        },
        selectedDate(date) {

            this.getListForUserList(date)
            this.currentTodayDate = date;
            this.getAllDatesOfCurrentMonth(this.currentTodayDate);

        },
        changeShowWeekOrMonth() {
            this.showMonthOrWeek = !this.showMonthOrWeek;
            this.getAllDatesOfCurrentMonth(this.currentTodayDate);
        },
        getAllDatesOfCurrentMonth(dateData) {
            this.getlistForMonth(moment(dateData).format('YYYY-MM'))
            const today = new Date(dateData);
            this.currentToday = new Date(today);
            this.currentYear = today.getFullYear();
            this.currentMonthNum = today.getMonth() + 1;
            this.currentMonth = today.getMonth() + 1 < 10 ? '0' + (today.getMonth() + 1) : today.getMonth() + 1;
            // 上个月天数
            const lastMonth = new Date(today.getFullYear(), today.getMonth() - 1, 1);
            this.lastMonthDateNumber = new Date(lastMonth.getFullYear(), lastMonth.getMonth() + 1, 0).getDate();
            // 下个月天数
            const nextMonth = new Date(today.getFullYear(), today.getMonth() + 1, 1);
            this.nextMonthDateNumber = new Date(nextMonth.getFullYear(), nextMonth.getMonth() + 1, 0).getDate();
            this.currentMonthAllDate = [];
            if (this.showMonthOrWeek) {
                // 显示周视图
                let day = today.getDay();
                let startDate = new Date(today.getFullYear(), today.getMonth(), today.getDate() - day);
                let endDate = new Date(today.getFullYear(), today.getMonth(), today.getDate() - day + 6);

                for (let i = new Date(startDate); i <= endDate; i.setDate(i.getDate() + 1)) {
                    const date = new Date(i);
                    const monthFlag =
                        date.getMonth() + 1 === this.currentMonthNum ? 'current' :
                            date.getMonth() + 1 > this.currentMonthNum ? 'last' : 'next';

                    this.currentMonthAllDate.push({
                        number: date.getDate(),
                        month: monthFlag,
                        date: new Date(date)
                    });
                }
            } else {
                // 显示月视图
                const firstDayOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);
                const lastDayOfMonth = new Date(today.getFullYear(), today.getMonth() + 1, 0);
                this.monthFirstDayCurrentWeek = firstDayOfMonth.getDay();
                this.monthFinallyDayCurrentWeek = lastDayOfMonth.getDay();

                // 补上前一个月的天数
                if (this.monthFirstDayCurrentWeek !== 0) {
                    const isLastYear = this.currentMonth === 1;
                    for (let i = 0; i < this.monthFirstDayCurrentWeek; i++) {
                        const prevMonthDay = this.lastMonthDateNumber - this.monthFirstDayCurrentWeek + 1 + i;
                        const year = isLastYear ? this.currentYear - 1 : this.currentYear;
                        const month = isLastYear ? 12 : this.currentMonth - 1;
                        this.currentMonthAllDate.push({
                            number: prevMonthDay,
                            month: 'last',
                            date: `${year}/${month}/${prevMonthDay}`
                        });

                    }
                }

                // 当前月天数
                for (let i = 1; i <= lastDayOfMonth.getDate(); i++) {
                    this.currentMonthAllDate.push({
                        number: i,
                        month: 'current',
                        date: new Date(today.getFullYear(), today.getMonth(), i)
                    });
                }

                // 补上下一个月的天数
                if (this.monthFinallyDayCurrentWeek !== 6) {
                    const isNextYear = this.currentMonth === 12;
                    const month = isNextYear ? 1 : this.currentMonth + 1;
                    const year = isNextYear ? this.currentYear + 1 : this.currentYear;

                    for (let i = 1; i <= 6 - this.monthFinallyDayCurrentWeek; i++) {
                        this.currentMonthAllDate.push({
                            number: i,
                            month: 'next',
                            date: `${year}/${month}/${i}`
                        });
                    }

                }

                this.currentMonthAllDate = this.currentMonthAllDate.map(item => {
                    // 修正：使用 item.date 而非 item.data
                    const currentDate = moment(item.date).format('YYYY-MM-DD');
                    // 存在则返回 1，否则返回 0
                    item.isPlan = this.monthTodoList.includes(currentDate) ? true : false;
                    return item;
                });
            }
        }
    }
};
</script>
<style scoped lang="scss">
/* 原样式保持不变 */
.calendarbBox {
    width: 735rpx;
    margin-left: 7.5rpx;
    display: flex;
    justify-content: space-around;
    flex-wrap: wrap;

    .singleDay {
        width: 105rpx;
        height: 87rpx;
        line-height: 87rpx;
        color: #333;
        font-size: 32rpx;
        font-weight: bold;
        text-align: center;
        position: relative;

        .dayTextB {
            color: #e1e1e1;
        }

        .dayTextA {
            // color: #fff;
        }

        .point {
            width: 12rpx;
            height: 12rpx;
            background-color: #0863f0a6;
            // border:1px 
            color: #e1e1e1;
            position: absolute;
            top: 65rpx;
            left: 50%;
            transform: translate(-50%, 0);
            border-radius: 50%;
        }

        .selectedDayBGColor {
            width: 87rpx;
            height: 87rpx;
            border: 1px solid #0863f0a6;
            border-radius: 50%;
            position: absolute;
            top: 0;
            left: 9rpx;
        }

        .pointA {
            background-color: #fff;
        }
    }
}

.arrowBox {
    width: 750rpx;
    height: 109rpx;
    line-height: 109rpx;
    position: relative;

    .arrowButtonRegion {
        width: 100rpx;
        height: 50rpx;
        line-height: 50rpx;
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        background-color: #00b488;
        border-radius: 10rpx;
        color: #fff;
        font-size: 28rpx;
        text-align: center;
    }
}

.titleBox {
    width: 750rpx;
    height: 92rpx;
    background-color: #fff;
    position: relative;
    padding-bottom: 60rpx;

    .title {
        position: absolute;
        left: 30rpx;
        top: 25rpx;
        color: #333;
        font-size: 53rpx;
        font-weight: bold;
        text-align: left;
    }
}

.week {
    width: 750rpx;
    height: 39rpx;
    color: #999;
    font-size: 32rpx;
    font-weight: bold;
    text-align: left;
    display: flex;
    justify-content: space-around;
    margin-left: 7.5rpx;
    margin-bottom: 49rpx;
}

.form-group {
    margin-bottom: 20rpx;

    input,
    textarea {
        border: 1px solid #ccc;
        padding: 10rpx;
        margin-top: 10rpx;
    }
}

.u-form-data {
    margin: 6vh 2vh;
    padding-left: 2px;
    max-height: 45vh;
    overflow-y: auto;
}

.u-form-item__body {
    .u-form-item__body__right__content__slot {

        input,
        view,
        textarea {
            font-size: 28rpx !important;
            color: #333 !important;
        }
    }
}
</style>